package com.emns.listener;

import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.emns.dao.LanmuMapper;
import com.emns.pojo.Lanmu;
import common.ConfigUtils;

public class EmnsApplicationListener implements ServletContextListener {

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// TODO Auto-generated method stub
		try {
			Reader reader = Resources.getResourceAsReader("mybatis.xml");
			SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
					.build(reader);
			// 打开一个会话
			SqlSession session = sessionFactory.openSession();
			LanmuMapper lanmu = session.getMapper(LanmuMapper.class);
			List<Lanmu> firstLanmu = lanmu.selectFrist();
			List<Lanmu> secondLanmu = lanmu.selectSecond();
			sce.getServletContext().setAttribute("firstLanmu", firstLanmu);
			sce.getServletContext().setAttribute("secondLanmu", secondLanmu);
			sce.getServletContext().setAttribute("yueduPicPath",
					ConfigUtils.getAppConfig("yuedu.picpath"));
			File file = new File(sce.getServletContext().getRealPath("/")
					+ ConfigUtils.getAppConfig("yuedu.picpath"));
			if (!file.exists())
				file.mkdirs();
			File fileYuedu = new File(sce.getServletContext().getRealPath("/")
					+ "userfiles/yueduPic");
			if (!fileYuedu.exists())
				fileYuedu.mkdirs();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// @Override
	// public void contextInitialized(ServletContextEvent sce) {
	// // TODO Auto-generated method stub
	// System.out.println("+++++++++++++");
	// WebApplicationContext wac = WebApplicationContextUtils
	// .getWebApplicationContext(sce.getServletContext());
	// // ZhihuiService map = wac.getBean(arg0, arg1)
	// // Zhihui zhihui = new Zhihui();
	// // zhihui.setContent("aaaaaaaa");
	// // zhihui.settUserUserId(1);
	// // map.addZhihui(zhihui);
	//
	// }

}
